package com.budwk.app.sqfwV2.generator.dayingRoadExcel;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.constants.DictConstants;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfwDoc.bo.SqfwExcelForSummaryBO;
import com.budwk.app.sqfwDoc.bo.SqfwExcelJudgeRes;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.BaseExcelParamDTO;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.BaseTemplateExcelGenerator;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.SqfwExcelCreateCommonBO;
import com.budwk.app.sqfwV2.component.DayingRoadPdfComponent;
import com.budwk.app.sqfwV2.component.ProblemComponent;
import com.budwk.app.sqfwV2.dto.dto.FireSafetyOnDayingRoadPdfDTO;
import com.budwk.app.sqfwV2.dto.dto.centuryCity.SafeCheckTaskParamDataDTO;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.ProblemParamDTO;
import com.budwk.app.sqfwV2.dto.image.FireSafetyOnDayingRoadExcelImageConfigBO;
import com.budwk.app.sqfwV2.enums.DayingRoadFileServiceEnum;
import com.budwk.app.sqfwV2.enums.RectificateTimeEnum;
import com.budwk.app.sqfwV2.enums.dayingRoad.OtherPatrolContentsEnum;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.StrUtil;
import com.budwk.app.util.poiUtils.excelPictureConfigBO.ExcelFileCreateParamBO;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * 11 附件4：城镇燃气餐饮用户台账表/Excel
 */

@Slf4j
public class UrbanGasGenerator extends BaseTemplateExcelGenerator implements DayingRoadExcelGenerator {

    @Override
    protected String getTemplateName() {
        return DayingRoadFileServiceEnum.DAYING_ROAD_EXCEL_CATER.getFilePath();
    }

    /**
    * 可以参照 {@link com.budwk.app.sqfw.enums.DownLoadFileNameEnum}
    *
    * @return 文件名名称
    */
    @Override
    public String getDownloadFileName() {
        //TODO 在这里返回你生成的文件名名称，注意注意注意不用带上后缀
        return DayingRoadPdfComponent.getDictName(DayingRoadFileServiceEnum.DAYING_ROAD_EXCEL_CATER.getCode(), null);
    }

    /**
     * 用户自定义excel基础参数，比如表头这样的公用数据
     * @param excelParam 已经填充的基础数据据
     * @param excelCreateParam excel生成提供的原料
     */
    @Override
    protected void customerPopularSheetBaseParam(Map<String, Object> excelParam, SqfwExcelCreateCommonBO excelCreateParam) {
        log.info("UrbanGasGenerator getBaseExcelParamDTO: {}", JSONObject.toJSONString(excelCreateParam.getBaseExcelParamDTO()));
        SysUserService userService = NutzIocUtils.getBean(SysUserService.class);
        Sys_user user = userService.fetch(excelCreateParam.getBaseExcelParamDTO().getCreateUserId());
        excelParam.put("street", excelCreateParam.getBaseExcelParamDTO().getCounty());
        excelParam.put("downloadData", DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
        BaseExcelParamDTO b = excelCreateParam.getBaseExcelParamDTO();
        excelParam.put("unitName", DayingRoadPdfComponent.getUnitName(b));
        excelParam.put("createUsernamePhone", user.getUsername() + " " + user.getMobile());
        excelParam.put("district", DayingRoadPdfComponent.getDistrict(excelCreateParam.getBaseExcelParamDTO().getDistrict()));
    }

    @Override
    protected void customerPopularSheetDataParam(List<Map<String, Object>> listMap, SqfwExcelCreateCommonBO excelCreateParam) {
        List<Sqfw_formSummary_new> summaryList = DayingRoadPdfComponent.getSummaryList(listMap, excelCreateParam);
        log.info("ThreeDetailedGenerator customerDataParam summaryList: {}", JSONObject.toJSONString(summaryList));
        int num = 1;
        for (Sqfw_formSummary_new summary : summaryList) {
            FireSafetyOnDayingRoadPdfDTO roadPdfDTO = JSONObject.parseObject(summary.getParamData(), FireSafetyOnDayingRoadPdfDTO.class);
            log.info("ThreeDetailedGenerator customerDataParam roadPdfDTO: {}", JSONObject.toJSONString(roadPdfDTO));
            if (!isGenerateExcel(roadPdfDTO)) {
                continue;
            }
            // 构建数据
            Map<String, Object> map = buildExcelMap(roadPdfDTO);
            map.put("num", num ++);
            listMap.add(map);
        }
        log.info("ThreeAndOneSiteGenerator customerDataParam end: {}", JSONObject.toJSONString(listMap));
    }

    private Map<String, Object> buildExcelMap(FireSafetyOnDayingRoadPdfDTO roadPdfDTO) {
        Map<String, Object> map = new HashMap<>();
        map.put("placeName", StrUtil.replaceNullStr(roadPdfDTO.getPlaceName()));
        map.put("address", StrUtil.replaceNullStr(roadPdfDTO.getAddress()));
        map.put("liquefiedGasNumber", StrUtil.replaceNullStr(roadPdfDTO.getLiquefiedGasNumber()));
        map.put("socialCreditCode", StringUtils.isBlank(roadPdfDTO.getSocialCreditCode()) ? "无执照" : "有执照");
        // 燃气存储地是否合规(含收市后存放
        ProblemParamDTO ppd = new ProblemParamDTO();
        map.put("gasStores", ProblemComponent.getGasStoreStr(roadPdfDTO, ppd));
        // 供气企业名称
        map.put("gasDeliveryCompanyName", DayingRoadPdfComponent.getDictName(roadPdfDTO.getGasDeliveryCompany(), null));

        // 供气企业是否开展入户安检及安全培
        map.put("othProblemStr", CommonConstants.HORIAONTAL_LINE);
        map.put("gasStovesStr", CommonConstants.HORIAONTAL_LINE);
        map.put("reserveFireSafety", CommonConstants.HORIAONTAL_LINE);
        map.put("safeDesc",CommonConstants.HORIAONTAL_LINE);
        String beenRectified = CommonConstants.HORIAONTAL_LINE;
        List<SafeCheckTaskParamDataDTO> others = roadPdfDTO.getOtherPatrolContents();
        if (others != null && others.size() > 0) {
            SafeCheckTaskParamDataDTO p = ProblemComponent.getSafeCheckTaskParamDataDTO(others, OtherPatrolContentsEnum.TWENTYFIVE.getCode());
            map.put("othProblemStr", p.getKey().equals("true")  ? "是" : "否"); // 供气企业是否开展入户安检及安全培
            map.put("gasStovesStr", ProblemComponent.getGasStovesStr(roadPdfDTO, ppd)); // 钢瓶、管道、灶具等燃气用户状况
            map.put("reserveFireSafety", ProblemComponent.getReserveFireSafety(roadPdfDTO, ppd));
            map.put("safeDesc", ProblemComponent.getSafeDescStr(roadPdfDTO, ppd)); // 是否存在安全隐患
            // 是否已整改
            for (SafeCheckTaskParamDataDTO other : others) {
                OtherPatrolContentsEnum e = OtherPatrolContentsEnum.getEnumByCode(other.getFields());
                if (other.getKey().equals(e.getDefaultValue())) {
                    continue;
                }
                if (RectificateTimeEnum.isDeadlineRectification(other, e.getDefaultValue())) {
                    beenRectified = "整改中";
                    break;
                }
                beenRectified = "已整改";
            }
        }
        map.put("beenRectified", beenRectified);
        map.put("operator", StrUtil.replaceNullStr(roadPdfDTO.getOperator()));
        map.put("operatorTelephone", StrUtil.replaceNullStr(roadPdfDTO.getOperatorTelephone()));
        return map;
    }

    /**
     * ●生成表格注意事项：
     * ○【用户用火用电情况】状态为【瓶装液化气】或【瓶装天然气】或【瓶装二甲醚】或【管道燃气】或【使用醇基燃料】的状态外且【a13】状态为【否】，生成表格。
     * @param roadPdfDTO
     * @return
     */
    public boolean isGenerateExcel(FireSafetyOnDayingRoadPdfDTO roadPdfDTO) {
        // 判断a5是否为重点场所 选择重点场所 不生成表格
        if (DayingRoadPdfComponent.isKeyLocations(roadPdfDTO)) {
            return false;
        }
        String fireAndElectricityUsage = roadPdfDTO.getFireAndElectricityUsage();
        if (StringUtils.isEmpty(fireAndElectricityUsage)) {
            return false;
        }
        // 使用燃气属于（1、瓶装液化气、2、瓶装天然气、3、瓶装二甲醚、4、管道燃气、5、使用醇基燃料）
        List<String> usageCodes = List.of(DictConstants.BOTTLED_GAS, DictConstants.NATURAL_GAS, DictConstants.BOTTLED_ETHER,
                DictConstants.BOTTLED_ETHER_ELECTRICITY_GAS, DictConstants.BOTTLED_GAS_FUELS);
        Optional<String> optional = usageCodes.stream().filter(fireAndElectricityUsage::contains).findAny();
        if (optional.isPresent()) {
            // 判断a13  isNightMarketStalls 是否为夜市游摊
            return roadPdfDTO.getIsNightMarketStalls() != null && !roadPdfDTO.getIsNightMarketStalls();
        }
        return false;
    }

    @Override
    protected void completeExcelFileCreateParam(ExcelFileCreateParamBO excelFileCreateParam) {

    }

    @Override
    protected void customerPopularRowDataMap(Map<String, Object> rowDataMap, SqfwExcelForSummaryBO forSummaryBO) {

    }

    /**
     * 如果在遍历之前就能够判断excel是否生成，那么就在这个方法中进行判断
     * @param excelCreateParam excel生成所需的最为全面的数据
     * @param excelParam excel已经填充的部分数据
     */
    @Override
    protected SqfwExcelJudgeRes judgeDataIntoExcelBeforeErgodic(SqfwExcelCreateCommonBO excelCreateParam, Map<String, Object> excelParam) {
        return DayingRoadPdfComponent.getSqfwExcelJudgeRes(excelCreateParam, new UrbanGasGenerator());
    }

    /**
     * 如果在遍历之后能够判断excel是否生成，那么就在这个方法中进行判断
     * @param excelParam excel已经填充的部分数据
     */
    @Override
    protected SqfwExcelJudgeRes judgeDataIntoExcelBeforeCreate(Map<String, Object> excelParam) {
        return null;
    }

    @Override
    protected Class<?> getImageConfigBO() {
        return FireSafetyOnDayingRoadExcelImageConfigBO.class;
    }
}
